import $http from "./request";
//import logger from '../utils/logger';
import { loadIM } from '@/api/IM/index'
export default{
	//用户token
	token:false,
	//用户id
	userIdPss:'',
	userMsg:'',
	// 初始化
	__init(){
		// 获取用户信息
		this.token = uni.getStorageSync("token");
		this.userIdPss = uni.getStorageSync('userIdPss');
	},
	// 权限验证跳转
	navigate(options,NoCheck = false,type = "navigateTo"){
		// 是否登录验证
		if (!$http.checkToken(true)){
			return; 
		}
		// 跳转
		switch (type){
			case "navigateTo":
			uni.navigateTo(options);
				break;
			case "redirectTo":
			uni.redirectTo(options);
				break;
			case "reLaunch":
			uni.reLaunch(options);
				break;
			case "switchTab":
			uni.switchTab(options);
				break;
		}
	},
	// 登录
	async login(options ={}){
		uni.showLoading({ title: '登录中...', mask: true });
		// 请求登录
		let [err,res] = await $http.post(options.url,options.data);
		// 登录失败
		if (!$http.errorCheck(err,res)){
			uni.hideLoading();
			return false;
		}
		uni.hideLoading();
		if(res.data.code == 200){
			// 登录成功 保存状态
			this.token = res.data.datas.token;
			this.userIdPss = res.data.datas.userId;
			uni.setStorageSync("token", this.token);
			uni.setStorageSync("userIdPss",this.userIdPss);
			uni.setStorageSync('logAcc',res.data.datas.account);
			uni.setStorageSync('userPortrait',res.data.datas.userPortrait);
			uni.setStorageSync('nickName',res.data.datas.netName);
			uni.showToast({ title: '登录成功' });
			uni.$emit('changeLoginStaToLogin');
			/* 执行即时通讯登录 */
			//this.__loadIM(res.data.datas.account);
			setTimeout(()=>{
				// 返回上一步
				if(options.opt == ''){
					uni.switchTab({
						url:'/pages/index/index' 
					})
					//if (!options.Noback) {}
				}else{
					if(Number( options.canRefreshFlag ) == 1){
						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2];
						prevPage.$vm.isRefreshFlag = true;
					}
					uni.navigateBack({ delta: 1 });
				}
			},1500);
			return true;
		}else if(res.data.code == 1000){
			uni.showToast({'title':'登录失败,服务器错误','icon':'none'});
		}else if(res.data.code == 10002){
			uni.showToast({'title':'登录失败,登录参数不能为空','icon':'none'});
		}else if(res.data.code == 10005){
			uni.showToast({'title':'登录失败,验证码不匹配','icon':'none'});
		}else if(res.data.code == 20002){
			uni.showToast({'title':'账号不存在或密码错误','icon':'none'});
		}else if(res.data.code == 20003){
			uni.showToast({'title':'该账号已注销或被禁用','icon':'none'});
		}else if(res.data.code == 20016){
			uni.showToast({'title':'当前身份不能在此设备登录','icon':'none'});
		}
		
	},
	__loadIM(userID){
		loadIM().then(res=>{ 
			//console.log(res)
			//uni.setStorageSync('userSingLogin',JSON.stringify( res ));
			this.__TUILogin(userID,res.data.msg);
		}).catch(err=>{
			console.log(err) 
		});
	},
	__TUILogin(userID,userSig){
		const SDKAppID = getApp().globalData.SDKAppID;
		getApp().globalData.userInfo = {
			userSig,
			userID
		};
		uni.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true);
		wx.$TUIKit.login({
			userID: userID,
			userSig: userSig
		}).then((imResponse) => {
			uni.removeStorageSync('IMRefuseNum');
		}).catch((error) => {
			uni.setStorageSync('IMRefuseNum',1);
		});
		if(!uni.getStorageSync('upIMHeadImg') && !uni.getStorageSync('IMRefuseNum')){
			uni.$on('isSDKReady', value => {
				if(value.isSDKReady){
					uni.$TUIKit.updateMyProfile({avatar: uni.getStorageSync('userPortrait'),nick:uni.getStorageSync('nickName')}).then(res => {
						//console.log(res)
						//更新成功后记录一个数据
						uni.setStorageSync('upIMHeadImg',1);
					}).catch(err=>{
						//console.log(err)
					});
				}
			});
		}
	},
	clearTokenStorage(opts){
		opts == undefined ? uni.showToast({'title':'授权登录过期,请重新登录','icon':'none'}) : '';
		this.clearStorage();
		uni.redirectTo({
			url:'/pages/login/login'
		}) 
	},
	clearStorage(){
		uni.removeStorageSync('userIdPss');
		uni.removeStorageSync('token');
		uni.removeStorageSync('logAcc');
		uni.removeStorageSync('provName');
		uni.removeStorageSync('cityName');
		uni.removeStorageSync('inviteCode');
		uni.removeStorageSync('userPortrait');
		uni.removeStorageSync('upIMHeadImg');
		uni.removeStorageSync('nickName');
		uni.removeStorageSync('userOpenId');
		//uni.removeStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`);
		this.token = false;
		this.userIdPss = '';
		/* 执行即时通讯退出接口 */
		uni.removeStorageSync('IMRefuseNum')
		//uni.$TUIKit.logout();
	}
}
